package com.mmg.sse_demo.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.exceptions.ExceptionUtil;
import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.db.Db;
import cn.hutool.db.Entity;
import cn.hutool.db.ds.DSFactory;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import cn.hutool.setting.Setting;
import com.mmg.sse_demo.entity.User;
import com.zaxxer.hikari.HikariDataSource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import javax.sql.DataSource;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

@CrossOrigin
@RestController
@Slf4j
public class SSEController {


    /**
     * 使用SSE协议实现获取用户信息
     */
    @GetMapping(value = "/get", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public SseEmitter getQQKey() {

        SseEmitter emitter = new SseEmitter();
        // 使用 Hutool 的 ThreadUtil 启动线程
        ThreadUtil.execAsync(() -> {
            try {
                List<User> userList = selectAllUsers();
                for (User user : userList) {
                    // 每个 user 作为事件推送到客户端
                    emitter.send(SseEmitter.event().name("data").data(user));
                    ThreadUtil.sleep(500); // 模拟延迟推送
                }
                emitter.complete(); // 结束推送
            } catch (Exception e) {
                log.error("SSE 推送失败: {}", ExceptionUtil.stacktraceToString(e)); // 记录异常日志
                emitter.completeWithError(e); // 出现异常时关闭推送
            }
        });
        return emitter;
    }

    public List<User> selectAllUsers() {
        List<User> userList = new ArrayList<>();
        try {
            // 执行查询
            HikariDataSource dataSource = new HikariDataSource();
            dataSource.setJdbcUrl("jdbc:mysql://localhost:3306/mumangguo");
            dataSource.setUsername("root");
            dataSource.setPassword("123456");
            dataSource.setMaximumPoolSize(10);

            Db db = Db.use(dataSource);

            List<Entity> entityList = db.query("SELECT * FROM user");
            String jsonString = JSONUtil.toJsonStr(entityList);
            System.out.println(jsonString);
            // 将 Entity 映射为 User 对象
            for (Entity entity : entityList) {
                User user = BeanUtil.toBean(entity, User.class);
                userList.add(user);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return userList;
    }

    public static void main(String[] args) throws SQLException {
        // 创建一个 HikariCP 数据源实例

    }

}
